package com.googlecode.websecuritychecks.testmodel;

import java.io.InputStream;
import java.util.UUID;

import javax.xml.parsers.DocumentBuilderFactory;

import com.googlecode.websecuritychecks.model.*;
import org.w3c.dom.*;

import com.googlecode.websecuritychecks.ParameterValueCheck;

public class InvalidParamValuesCheckUtil {

    public static void verifyAllInvalidValues(final String[] invalidValues, final InputStream checksInputXmlFileStream) throws Exception {

        Document document = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(checksInputXmlFileStream);
        document.normalizeDocument();
        Element ruleXmlFragment = document.getDocumentElement();
        Check check = new ParameterValueCheck();

        for (String invalidValue : invalidValues) {
            MockHttpServletRequest rq = new MockHttpServletRequest();
            MockHttpServletResponse rs = new MockHttpServletResponse();
            rq.addParam(UUID.randomUUID().toString(), new String[] { invalidValue });
            check.check(ruleXmlFragment, rq, rs);

            NodeList invalidParameterValueCheck = document.getElementsByTagName("InvalidParameterValueCheck");
            if (invalidParameterValueCheck != null && invalidParameterValueCheck.getLength() == 1) {
                Node invalidParameterValueCheckNode = invalidParameterValueCheck.item(0);
                String failureStatusCode = invalidParameterValueCheckNode.getAttributes().getNamedItem("failureStatusCode").getNodeValue();
                if (rs.getStatus() != Integer.parseInt(failureStatusCode)) {
                    throw new AssertionError("HTTP Status code: " + failureStatusCode + " expected for " + invalidValue + " But was: " + rs.getStatus());
                }
            }
        }
    }

}
